package com.example.hcd;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.example.hcd.adapt.ViewUtils;
import com.example.hcd.datamanage.JPushMessage;
import com.example.hcd.datamanage.MenuManage;
import com.example.hcd.datamanage.UserInfo;
import com.example.hcd.functionactivity.AddressBookActivity;
import com.example.hcd.functionactivity.BaseActivity;
import com.example.hcd.functionactivity.MyTaskList;
import com.example.hcd.functionactivity.NoticeDetailActivity;
import com.example.hcd.functionactivity.NoticeListActivity;
import com.example.hcd.functionactivity.SelectPicActivity;
import com.example.hcd.functionactivity.TaskInfo;
import com.example.hcd.functionactivity.UpdateManager;
import com.example.hcd.internet.InternetKeep;
import com.example.hcd.internet.LinkHelp;
import com.example.hcd.internet.URLS;
import com.example.hcd.menuactivity.AdminstrteMneuActivity;
import com.example.hcd.menuactivity.OptionMenuActivity;
import com.example.hcd.menuactivity.PersonalWorkAttendanceMenuActivity;
import com.example.hcd.menuactivity.WorkFlowMenuActivity;
import com.example.hcd.tool.Constants;
import com.example.hcd.tool.MenuScrollView;
import com.example.hcd.tool.MenuScrollView.SizeCallback;
import com.example.hcd.tool.MyLoadingDialog;
import com.example.hcd.tool.ToastHelp;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;

//import org.json.JSONObject;

public class MenuActivity extends BaseActivity {
    // 实例化自定义抽屉式scroview
    static private MenuScrollView menuScrollView;
    // 创建工作菜单与通知菜单
    private View work_menu_view;
    private View notice_menu_view;
    static public MenuActivity mContext;

    // 点击图片按钮
    private ImageView back_to_workmenu_btn;
    // 放置图片缓存
    private File mPhotoCache;
    // 图片路径
    private String mImagePath;
    // 获取到图片
    private Bitmap mBitmap;
    // 头像
    private ImageView mPhoto;

    /***
     * 选择图片
     */
    public static final int SELECT_PHOTO = 2;

    // private HttpMultipartPost post;
    private static boolean isOpen = false;

    // 设置广播机制
    //public static final String RECRIVE_BROADCAST = "receive_broadcast";

    private int unreadNotice = 0;
    private int undoTask = 0;

    private TextView noticenum;
    private TextView allnum;
    private TextView tasknum;

    //在handler中更新UI
    public static Handler mHandler;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        mPageName = "MenuActivity";
        mContext = this;
        // JPUSH 设置


        //获取系统信息
        InternetKeep.getInstence().getSystemInfo();

        // inflater 是用来找 res/layout 下的 xml 布局文件，并且实例化；
        LayoutInflater inflater = LayoutInflater.from(this);

        menuScrollView = (MenuScrollView) inflater.inflate(R.layout.menu_scorll_view, null);

        setContentView(menuScrollView);

        work_menu_view = inflater.inflate(R.layout.work_menu_view, null);

        menuScrollView.initMenuView(work_menu_view);
        notice_menu_view = inflater.inflate(R.layout.notice_menu_view, null);


        noticenum = (TextView) notice_menu_view.findViewById(R.id.noticenum);
        tasknum = (TextView) notice_menu_view.findViewById(R.id.tasknum);
        allnum = (TextView) notice_menu_view.findViewById(R.id.allnum);


        ListView listView = (ListView) work_menu_view.findViewById(R.id.list);
        mPhoto = (ImageView) work_menu_view.findViewById(R.id.photo_btn);

        ViewUtils view1 = new ViewUtils(this, R.layout.work_menu_item);

        view1.setList(MenuManage.getInstence().getMainMenu(this, MenuManage.getInstence().menuId));
        listView.setAdapter(view1);

        listView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//				ListView listView = (ListView) parent;
                switch (position) {
                    case 0:
                        Intent intent = new Intent(mContext, AdminstrteMneuActivity.class);
                        startActivity(intent);
                        break;

                    case 1: {
                        Intent intent1 = new Intent(mContext, WorkFlowMenuActivity.class);
                        startActivity(intent1);
                    }

                    break;

                    case 2:
                        Intent intent2 = new Intent(mContext, OptionMenuActivity.class);
                        startActivity(intent2);
                        break;

                    default:
                        break;
                }
            }
        });

        // 设置图片点击事件
        back_to_workmenu_btn = (ImageView) notice_menu_view.findViewById(R.id.back_to_workmenu_btn);
        back_to_workmenu_btn.setOnClickListener(new ClickListenerForScrolling(menuScrollView, work_menu_view));

        View[] view = {work_menu_view, notice_menu_view};
        menuScrollView.initViews(view, 0, new SizeCallbackForMenu(back_to_workmenu_btn));

        work_menu_view.findViewById(R.id.option_btn).setOnClickListener(mClickListener);

        work_menu_view.findViewById(R.id.out_login_btn).setOnClickListener(mClickListener);
        work_menu_view.findViewById(R.id.photo_btn).setOnClickListener(mClickListener);

        notice_menu_view.findViewById(R.id.notice_btn).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                Intent intent1 = new Intent(MenuActivity.this, NoticeListActivity.class);
                intent1.putExtra("TYPE_NOTICE", "notRead");
                startActivity(intent1);
            }
        });

        notice_menu_view.findViewById(R.id.address_book_btn).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                Intent intent5 = new Intent(MenuActivity.this, AddressBookActivity.class);
                startActivity(intent5);

            }
        });

        notice_menu_view.findViewById(R.id.tasktodo_btn).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(MenuActivity.this, MyTaskList.class);
                intent.putExtra("TASK_TYPE", "all_task_todo");
                startActivity(intent);
            }
        });

        notice_menu_view.findViewById(R.id.personal_btn).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(MenuActivity.this, PersonalWorkAttendanceMenuActivity.class);
                startActivity(intent);
            }
        });

        // 刷新用户信息
        refreshUserInfo();


        mHandler = new Handler() {
            public void handleMessage(Message msg) {
                //刷新公告
                mContext.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        LoadNum();
                    }
                });
            }

            ;
        };
//		registerBoradcastReceiver();
        //刷新公告
        LoadNum();


        Update();


        if (getIntent().hasExtra(Constants.NOTIFICATION)) {
            JPushMessage mNotification = (JPushMessage) getIntent().getSerializableExtra(Constants.NOTIFICATION);
            if (mNotification.getPush_type().equals("process")) {
                Intent intent = new Intent(this, TaskInfo.class);
                intent.putExtra("taskId", mNotification.getTaskId());
                intent.putExtra("processId", mNotification.getProcessInstanceId());
                intent.putExtra("TASK_TYPE", mNotification.getProcessType());
                intent.putExtra("IS_TASK_TODO", mNotification.getIsTaskToDo());
                startActivity(intent);
            } else {
                Intent intent = new Intent(this, NoticeDetailActivity.class);
                intent.putExtra(Constants.NOTIFICATION, mNotification);
                startActivity(intent);
            }
        }

    }

    private void Update() {
        UpdateManager um = new UpdateManager(this);
        um.findUpdata();
    }

    public static void sendMsg() {
        Message msg = new Message();

        mHandler.sendMessage(msg);
    }

    public void refreshUserInfo() {
        UserInfo user = UserInfo.getUserInfor();
        TextView realName = (TextView) work_menu_view.findViewById(R.id.realname);
        realName.setText("Hi," + user.getName());

        if (user.getmBitmap() == null) {
            LoadHeadPic UserInfoLoad = new LoadHeadPic();
            UserInfoLoad.execute();
        } else {
            UserInfo.getUserInfor().loadHeaderPhotos(mPhoto, user.getmBitmap());
        }

    }

    private OnClickListener mClickListener = new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            switch (arg0.getId()) {
                case R.id.option_btn:
                    Intent intent2 = new Intent(mContext, OptionMenuActivity.class);
                    startActivity(intent2);

                    break;
                case R.id.out_login_btn: {
                    new AlertDialog.Builder(MenuActivity.this).setMessage("是否退出？")
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                }
                            }).setPositiveButton("确定", new DialogInterface.OnClickListener()

                    {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            UserInfo.getUserInfor().setmBitmap(null);
                            UserInfo.getUserInfor().setIsLogin(false);
                            Set<String> sets = new HashSet<>();
                            JPushInterface.setAliasAndTags(VenadaOAApplication.getInstance(), "", sets);
                            new LogOutTask().execute();
//                            JPushInterface.stopPush();
                            //unregisterReceiver(mBroadcastReceiver);
                            finish();
                        }
                    }).show();
                }
                break;

                case R.id.photo_btn: {
                    Intent intent = new Intent(MenuActivity.this, SelectPicActivity.class);
                    intent.putExtra("type", "chooseone");
                    startActivityForResult(intent, SELECT_PHOTO);
                    overridePendingTransition(R.anim.out_alpha, R.anim.enter_alpha);
                }

                break;

                default:
                    break;
            }

        }
    };

    @Override
    protected void onStop() {
        //unregisterReceiver(mBroadcastReceiver);
        super.onStop();
    }


    static class ClickListenerForScrolling implements OnClickListener {
        HorizontalScrollView scrollView;
        View menu;

        /**
         * Menu must NOT be out/shown to start with.
         */

        public ClickListenerForScrolling(HorizontalScrollView scrollView, View menu) {
            super();
            this.scrollView = scrollView;
            this.menu = menu;
        }

        @Override
        public void onClick(View v) {
            Context context = menu.getContext();

            int menuWidth = menu.getMeasuredWidth();

            // Ensure menu is visible
            menu.setVisibility(View.VISIBLE);

            if (menuScrollView.isOpen) {
                // Scroll to 0 to reveal menu
                int left = 0;
                scrollView.smoothScrollTo(left, 0);
            } else {
                // Scroll to menuWidth so menu isn't on screen.
                int left = menuWidth;
                scrollView.smoothScrollTo(left, 0);
            }
            menuScrollView.isOpen = !menuScrollView.isOpen;
        }
    }

    /**
     * Helper that remembers the width of the 'slide' button, so that the
     * 'slide' button remains in view, even when the menu is showing.
     */
    static class SizeCallbackForMenu implements SizeCallback {
        int btnWidth;
        View btnSlide;

        public SizeCallbackForMenu(View btnSlide) {
            super();
            this.btnSlide = btnSlide;
        }

        @Override
        public void onGlobalLayout() {
            btnWidth = btnSlide.getMeasuredWidth();
            System.out.println("btnWidth=" + btnWidth);
        }

        @Override
        public void getViewSize(int idx, int w, int h, int[] dims) {
            dims[0] = w;
            dims[1] = h;
            final int menuIdx = 0;
            if (idx == menuIdx) {
                dims[0] = w - btnWidth - 60;
            }
        }
    }

    /*
     * 裁剪图片
     */
    private void startCrop(String path) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(Uri.fromFile(new File(path)), "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("return-data", true);
        intent.putExtra("outputX", 160);
        intent.putExtra("outputY", 160);
        intent.putExtra("aspectX", 1);// 裁剪框比例
        intent.putExtra("aspectY", 1);
        startActivityForResult(intent, 1002);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {

                // 裁剪返回的信息
                case 1002:
                    if (data != null) {
                        if (data.hasExtra("data")) {
                            mBitmap = data.getParcelableExtra("data");
                            if (mBitmap != null) {
                                System.out.println("上传服务器");
                                UpdateLoadHead2 task = new UpdateLoadHead2();
                                task.execute();
//							 UserInfo.getUserInfor().loadHeaderPhotos(mPhoto,
//							 mBitmap);
//							 UserInfo.getUserInfor().setPhotoChange(true);
                            } else {
                                //Toast.makeText(mContext, "替换失败", Toast.LENGTH_SHORT).show();
                                ToastHelp.doToastInTop(mContext, "替换失败");
                            }
                        }

                    }
                    break;

                case SELECT_PHOTO:
                    ArrayList<String> imagePaths = data.getStringArrayListExtra(SelectPicActivity.KEY_PHOTO_PATH);
                    mImagePath = imagePaths.get(0);

                    System.out.println("最终选择的图片=" + mImagePath);

                    startCrop(mImagePath);
                    break;

                default:
                    break;
            }
        } else if (resultCode == 1234) {

        }
    }


    private class LogOutTask extends AsyncTask<Void, Integer, String>{
        private String result;
        @Override
        protected String doInBackground(Void... params) {
            try {

                    result = null;
                    HttpResponse response = null;
                    BufferedReader reader = null;

                    try {
                        ArrayList<NameValuePair> vs = new ArrayList<NameValuePair>();
                        vs.add(new BasicNameValuePair("userId",UserInfo.getUserInfor().getId()));
                        response = LinkHelp.post(URLS.getLoginOut(),vs,false);

                        if (response != null) {

                            StatusLine line = response.getStatusLine();
                            if (line.getStatusCode() == 200) {
                                InputStream in = response.getEntity().getContent();
                                byte[] data = readStream(in);
                                result = new String(data);

                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        if (reader != null) {
                            try {
                                reader.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }


            } catch (Exception e) {
                e.printStackTrace();
            }
            return result;
        }

        @Override
        protected void onPostExecute(String s) {

            super.onPostExecute(s);
            InternetKeep.getInstence().clearCacheData();
            InternetKeep.getInstence().isSystemInfoLoad =false;
        }
    }

    /*
     * 传送头像到服务器
     */
    private class UpdateLoadHead2 extends AsyncTask<Void, Integer, String> {
        private String result;
        private MyLoadingDialog myLoaddialog;

        @Override
        protected void onPreExecute() {
            myLoaddialog = new MyLoadingDialog(MenuActivity.this, null, "提交中...", false);
            super.onPreExecute();

        }

        @Override
        protected String doInBackground(Void... params) {

            try {
                if (mBitmap != null) {
                    result = null;
                    HttpResponse response = null;
                    BufferedReader reader = null;

                    try {

                        response = LinkHelp.uploadPhoto(URLS.upLoadPhoto(), mBitmap, true);

                        if (response != null) {

                            StatusLine line = response.getStatusLine();
                            if (line.getStatusCode() == 200) {
                                InputStream in = response.getEntity().getContent();
                                byte[] data = readStream(in);
                                result = new String(data);

                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        if (reader != null) {
                            try {
                                reader.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return result;
        }

        @Override
        protected void onPostExecute(String result) {
            myLoaddialog.dimiss();
            super.onPostExecute(result);
            System.out.println(result);
            // mProgress.dismiss();

            if (result == null) {
                ToastHelp.doToast(MenuActivity.this, "网络异常！");
                return;
            }
            if (result.contains("success")) {
                // 上传成功
                System.out.println("上传成功");
                UserInfo.getUserInfor().loadHeaderPhotos(mPhoto, mBitmap);
                UserInfo.getUserInfor().setPhotoChange(true);
            } else if (result.contains("error")) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String msg = jsonObject.getString("msg");
                    //Toast.makeText(MenuActivity.this, msg, Toast.LENGTH_SHORT).show();
                    ToastHelp.doToastInTop(mContext, msg);
                } catch (Exception e) {
                    // TODO: handle exception
                }

            }
        }
    }

    private class LoadHeadPic extends AsyncTask<String, Integer, String> {

        private final String CODE = "code";
        private Bitmap bitmap = null;

        @Override
        protected void onPreExecute() {

        }

        public void cancel() {

        }

        @Override
        protected String doInBackground(String... params) {
            String result = null;
            HttpResponse response = null;
            BufferedReader reader = null;

            try {

                response = LinkHelp.post(URLS.getPhoto(), null, false);

                if (response != null) {

                    StatusLine line = response.getStatusLine();
                    if (line.getStatusCode() == 200) {
                        InputStream in = response.getEntity().getContent();
                        byte[] data = readStream(in);
                        result = new String(data);

                        if (result.contains("error")) {
                            try {
                                JSONObject jsonObject = new JSONObject(result);
                                String msg = jsonObject.getString("msg");
                                //Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
                                ToastHelp.doToastInTop(mContext, msg);
                            } catch (Exception e) {
                                // TODO: handle exception
                            }
                        } else {
                            this.bitmap = BitmapFactory.decodeByteArray(data, 0, data.length); // 生成位图
                        }

                        return result;

                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return result;
        }

        @Override
        protected void onPostExecute(String result) {

            int errorId = -1;
            if (!TextUtils.isEmpty(result)) {
                if (result.contains("error")) {

                } else {
                    UserInfo.getUserInfor().loadHeaderPhotos(mPhoto,
                            this.bitmap);
                    UserInfo.getUserInfor().setPhotoChange(true);
                }
            } else {

                if (result == null) {

                    System.out.println("result == null");
                } else {

                }

            }
        }

    }

    public static byte[] readStream(InputStream in) throws Exception {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = in.read(buffer)) != -1) {
            outputStream.write(buffer, 0, len);
        }
        outputStream.close();
        in.close();
        return outputStream.toByteArray();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub if(keyCode == KeyEvent.KEYCODE_BACK){
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            moveTaskToBack(true);
            return true;
        } else {
            return super.onKeyDown(keyCode, event);
        }

    }

//	// 注册广播接收机制
//	private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
//		@Override
//		public void onReceive(Context context, Intent intent) {
//			String action = intent.getAction();
//			if (action.equals(RECRIVE_BROADCAST)) {
//				LoadNum();
//			}
//		}
//
//	};
//
//	// 注册广播
//	public void registerBoradcastReceiver() {
//		IntentFilter myIntentFilter = new IntentFilter();
//		myIntentFilter.addAction(RECRIVE_BROADCAST);
////		unregisterReceiver(mBroadcastReceiver);
//		// 注册广播
//		registerReceiver(mBroadcastReceiver, myIntentFilter);
//	}

    // 加载数量
    private void LoadNum() {
        LoadTaskNum load = new LoadTaskNum();
        load.execute();
    }

//	public void onReceive(Context context, Intent intent) {
////		context.unregisterReceiver(mBroadcastReceiver);
//	}

    //舒心数量
    private void refreshNum() {

        String num;
        if (unreadNotice > 0) {
            num = "" + unreadNotice;
            noticenum.setVisibility(View.VISIBLE);
            noticenum.setText(num);
        } else {
            noticenum.setVisibility(View.GONE);
        }

        if (undoTask > 0) {
            num = "" + undoTask;
            tasknum.setVisibility(View.VISIBLE);
            tasknum.setText(num);
        } else {
            tasknum.setVisibility(View.GONE);
        }

        int all = unreadNotice + undoTask;
        if (all > 0) {
            num = "" + all;
            allnum.setVisibility(View.VISIBLE);
            allnum.setText("" + all);
        } else {
            allnum.setVisibility(View.GONE);
        }


    }

    private class LoadTaskNum extends AsyncTask<String, Integer, String> {

        @Override
        protected void onPreExecute() {

        }

        @Override
        protected String doInBackground(String... params) {
            String result = null;
            HttpResponse response = null;
            BufferedReader reader = null;

            try {

                response = LinkHelp.post(URLS.getNumofTask(), null, false);

                if (response != null) {

                    StatusLine line = response.getStatusLine();
                    if (line.getStatusCode() == 200) {
                        InputStream in = response.getEntity().getContent();
                        byte[] data = readStream(in);
                        result = new String(data);

                        return result;

                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return result;
        }

        @Override
        protected void onPostExecute(String result) {

            int errorId = -1;
            if (!TextUtils.isEmpty(result)) {
                if (result.contains("error")) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        String msg = jsonObject.getString("msg");
                        //Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
                        ToastHelp.doToastInTop(mContext, msg);
                    } catch (Exception e) {
                        // TODO: handle exception
                    }
                } else {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        unreadNotice = jsonObject.getInt("notification");

                        undoTask = jsonObject.getInt("task");

                        //refreshNum();
                    } catch (Exception e) {
                        // TODO: handle exception
                    }
                }
            } else {

                if (result == null) {

                    System.out.println("result == null");
                } else {

                }

            }


            refreshNum();
        }

    }

}
